package com.idcheck.rechcustoms;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.idcheck.rechcustoms.tessOcrUtil.MyGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import utils.PrefUtils;

import static com.idcheck.rechcustoms.FullscreenActivity.getWeek;

public class GridListActivity extends AppCompatActivity {
    LinearLayout tv_back;
    private List<CabDetailModel> mList = new ArrayList<>();
    private CabDetailAdapter cabDetailAdapter;
    private MyGridView cab_grid_view;
    private Button openbtn;
    private Button backbtn;
    private boolean hasChoose = false;
    private String cabinetgridid = "";
    private CountDownTimer mTimer=null; //UI计时
    private volatile long resetTimeStamp = 0;
    private volatile long brightTimeStamp = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_list);

        if (getSupportActionBar() != null) {

            getSupportActionBar().hide();

        }
        hideBottomUIMenu();

        initTimer();

        tv_back = (LinearLayout) findViewById(R.id.ll_back);
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message = new Message();
                message.what=2200;
                EventBus.getDefault().post(message);
                finish();
            }
        });

        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        companyCabDetail();

        cab_grid_view=findViewById(R.id.cab_grid_view);

        cab_grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                if(null!=mList&&mList.size()>0){

//                    BaseApplication.getIntance().setmCabDetailModel(mList.get(position));
//                    startActivity(new Intent(ChioceCabActivity.this, CabInfoActivity.class));


                }




            }
        });

        openbtn = (Button) findViewById(R.id.openbtn);
        openbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).isChoose()) {
                        hasChoose = true;
                        cabinetgridid = mList.get(i).getCabinetgridid();
                    } else {
                        continue;
                    }
                }
                if (hasChoose) {
                    new FetchlanzhengOpenGridTask(cabinetgridid).execute();
                } else {
                    Toast.makeText(GridListActivity.this,"请选择一个格子",Toast.LENGTH_SHORT).show();
                }
            }
        });

        backbtn = (Button) findViewById(R.id.backbtn);
        backbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message message = new Message();
                message.what=2200;
                EventBus.getDefault().post(message);
                finish();
            }
        });
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {

            Window _window = getWindow();
            WindowManager.LayoutParams params = _window.getAttributes();
            params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
            _window.setAttributes(params);
        }
    }

    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (9999999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    if (!GridListActivity.this.isFinishing()) {
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 \n HH:mm:ss");// HH:mm:ss
//获取当前时间
                        Date date = new Date(System.currentTimeMillis());
                        TextView datetext = (TextView)findViewById(R.id.textDate);
                        datetext.setText(simpleDateFormat.format(date));
                        TextView weektext = (TextView)findViewById(R.id.textWeek);
                        weektext.setText(getWeek());
                        if(brightTimeStamp != 0){
                            long totalMilliSeconds = System.currentTimeMillis();
                            long timeOut = totalMilliSeconds - brightTimeStamp;
                            if(timeOut > 3600000){
                                int hours = date.getHours();
                                int minutes = date.getMinutes();
                                int seconds = date.getSeconds();
                                brightTimeStamp = 0;
                            }
                        }
                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    private void companyCabDetail() {
        new FetchCompanyCabDetailTask(PrefUtils.getString(GridListActivity.this, "adminid", "0")).execute();
    }

    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message) {
        switch (message.what) {
            case 2300:
                EventMessageForlanzhengList(message.obj);
                break;
            case 2400:
                EventMessageForlanzhengOpenGrid(message.obj);
                break;
            default:
                //EventMessageForError(message.what);
                break;

        }
    }

    private void EventMessageForlanzhengOpenGrid(Object obj) {
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                Toast.makeText(GridListActivity.this,result.getString("msg"),Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(GridListActivity.this,result.getString("msg"),Toast.LENGTH_LONG).show();
            }

        }catch(Exception e){
        }
    }

    private void EventMessageForlanzhengList(Object obj) {
        mList.clear();
        try{
            JSONObject result = new JSONObject(obj.toString());
            if(result.getString("code").equals("100")){
                JSONArray orders = result.getJSONArray("data");
                for(int i=0; i<orders.length(); i++){
                    JSONObject jsonObject1 = orders.getJSONObject(i);
                    CabDetailModel addressModule = new CabDetailModel();
                    addressModule.setGridnum(jsonObject1.get("gridNum").toString());
                    addressModule.setIsuse(jsonObject1.get("isUse").toString());
                    addressModule.setCabinetgridid(jsonObject1.get("cabinetGridId").toString());
                    addressModule.setChoose(false);
                    mList.add(addressModule);
                }


                cab_grid_view.setVisibility(View.VISIBLE);
                CabDetailAdapter adapter = new CabDetailAdapter(GridListActivity.this,mList);
                cab_grid_view.setAdapter(adapter);
            } else {
                cab_grid_view.setVisibility(View.GONE);
            }


        }catch(Exception e){
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unInitTimer();
    }
}
